// import Vue from 'vue'
// import VueRouter from 'vue-router'
import store from '@/store';
import _ from 'lodash';

import { getPageTitle, notify } from '@/utils';
import { requestQueue } from '@/utils/requestQueue';
import routes from './routes';
import {
  ACCOUNT_DEFAULT_MENU,
  isAnyRoles,
  getAccountRouteByRolesName,
  getRouteNameByRouteCode,
  getRoleNameByPermissionRouters,
  isRouteNameInMenuRoute
} from '@/config/permission';

// 修改掉 VueRouter原型上的push方法, 把异常抓住, 啥也不做
// 解决 Error: Navigation aborted 报错
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject);
  }
  return originalPush.call(this, location).catch(err => err);
};

Vue.use(VueRouter);

// 如果meta中没有needLogin属性，取此默认值
const defaultNeedLogin = true;

const router = new VueRouter({
  routes
});

// 获取地址栏上的参数
function GetRequest (value, defaultUrl) {
  var url = defaultUrl || window.location.href;
  var object = {};
  if (url.indexOf('?') !== -1) {
      var str = url.split('?')[1];
      var strs = str.split('&');
      for (var i = 0; i < strs.length; i++) {
          object[strs[i].split('=')[0]] = strs[i].split('=')[1];
      }
  }
  return object[value];
}
// const VueRouterPush = VueRouter.prototype.push;

// VueRouter.prototype.push = function push (to) {
//   return VueRouterPush.call(this, to).catch(err => err);
// };

const errorMsgLogin = 'pleaseLogin';

const noRightTo = {
  path: '/401'
};

// 是否需要登录
function shouldLogin (to) {
    let needLogin = to.meta.needLogin;
    if (needLogin === undefined) {
        needLogin = defaultNeedLogin;
    }
    return needLogin;
}

// 是否需要签署《合格投资者承诺书》
function shouldSignCommitment (to) {
  /**
   * 判断
   * 1.该路由是否需要签署承诺书(commitment判断)；
   * 2.是否已签署承诺书
   */
  if (to.meta.commitment && localStorage.getItem('VINTEX_commit') !== '1') {
    store.commit('updateShowCommitment', true);
    store.commit('updatePathCommitment', to.fullPath);
    return false;
  } else {
    return true;
  }
}

/**
 * 验证用户是否有访问这个路由的权限
 * @param {*} to - 要访问的路由
 * @param {*} rolesName - 用户角色数组
 * @returns {Promise}
 */
async function hasRight (to, rolesName, next) {
  try {
    await accountRedirect(to, rolesName, next);
    if (to.meta.roles) {
      await verifyPermissionRouters(to, next);
    }
    await verifySwitch(to, next);
    await signFlag(to, next);
    if (to.meta.roles) {
      hasRole(to, rolesName, next);
    } else {
      next();
    }
  } catch (e) {
  }

  // 用户中心，重定向
  function accountRedirect (to, rolesName, next) {
    return new Promise((resolve, reject) => {
      if (to.path === '/account' && isAnyRoles(rolesName)) {
        const currentRole = store.getters.currentRole;
        let redirectRouteName = '';
        if (currentRole) {
          redirectRouteName = ACCOUNT_DEFAULT_MENU[currentRole];
        } else {
          redirectRouteName = getAccountRouteByRolesName(rolesName);
        }
        if (redirectRouteName) {
          const route = { name: redirectRouteName };
          next(route);
          reject(new Error('重定向至' + redirectRouteName));
        }
      }
      resolve();
    });
  }

  // 我的账户，根据当前角色验证菜单权限
  function verifyPermissionRouters (to, next) {
    return new Promise((resolve, reject) => {
      const { name: routerName } = to;
      const { currentRole, permissionRouters } = store.getters;
      const isInMenu = isRouteNameInMenuRoute(routerName);
      if (!isInMenu) {
        // 如果路由不在左侧菜单内，无需判断是否有菜单权限
        resolve();
        return;
      }
      const currentRoutesName = getRouteNameByRouteCode(permissionRouters[currentRole]);
      const noMenuPermission = !currentRoutesName.includes(routerName);
      if (noMenuPermission) {
        const changeRole = getRoleNameByPermissionRouters(routerName, permissionRouters);
        if (changeRole) {
          store.commit('permission/SET_CURRENT_ROLE', changeRole);
        } else {
          next(noRightTo);
          reject(new Error(`当前角色没有当前路由权限${changeRole}:${routerName}`));
        }
      }
      resolve();
    });
  }

  // 判断路由开关是否开启
  function verifySwitch (to, next) {
    return new Promise((resolve, reject) => {
      if (to.meta.switch !== undefined && !to.meta.switch) {
        next(false);
        notify('暂未开放，敬请期待', 'info');
        reject(new Error('路由开关关闭'));
      }
      resolve();
    });
  }

  // 是否需要签署承诺书
  function signFlag (to, next) {
    return new Promise((resolve, reject) => {
      const flag = shouldSignCommitment(to);
      if (!flag) {
        next(false);
        reject(new Error('取消签署'));
      }
      resolve();
    });
  }

  // 兜底，判断是否有角色
  function hasRole (to, rolesName, next) {
    const hasPermission = _.intersection(rolesName, to.meta.roles).length > 0;
    if (hasPermission) {
      // 有权限
      next();
    } else {
      next(noRightTo);
    }
  }
}

router.beforeEach(async (to, from, next) => {
    // 更新userClient
    const userClient = GetRequest('userClient');
    if (userClient) {
      store.commit('updateUserClient', userClient);
    }
    // 页面跳转取消所有未完成的接口请求
    requestQueue.cancelRequest();
    // 设置页面标题
    document.title = getPageTitle(to.meta.title);

    // 将路由历史加入缓存
    const fromRouterArr = localStorage.getItem('fromRouter') && JSON.parse(localStorage.getItem('fromRouter')) || [];
    if (fromRouterArr.length === 0) {
      fromRouterArr.push({
        title: to.meta.title,
        path: to.path
      });
    } else {
      if (fromRouterArr[fromRouterArr.length - 1].path !== to.path) {
        if (fromRouterArr.length >= 2) {
          fromRouterArr.shift();
        }
        fromRouterArr.push({
          title: to.meta.title,
          path: to.path,
          name: to.name,
          params: to.params,
          meta: to.meta
        });
      }
    }
    localStorage.setItem('fromRouter', JSON.stringify(fromRouterArr));

    // 已登录
    if (store.state.userInfo) {
      // 暂时注释权限相关代码
      // // 权限判断
      // hasRight(to, store.getters.rolesName, next);

      next(); // 权限注释后替代代码（权限启用后删除）
      return;
    }
    // 需要登录
    if (shouldLogin(to)) {
      store.dispatch('login').then(() => {
        // 暂时注释权限相关代码
        // store.dispatch('permission/get').then(() => {
        //   hasRight(to, store.getters.rolesName, next);
        // });

        next(); // 权限注释后替代代码（权限启用后删除）
      }).catch(err => {
        // 登录失败
        if (err && err.message === errorMsgLogin) {
          next({ path: '/login', query: { redirect: to.path } });
        } else {
          next({ path: '/error', query: { error: '无法访问' } });
        }
      });
    } else {
      // 无需登录
      next();
    }
});
router.afterEach((to, from) => {
  if (to.query.prodCode || !to.meta.jumpDisableScroll || !from.meta.jumpDisableScroll) {
    window.scrollTo(0, 0);
  };
  // 暂时注释权限相关代码
  // store.dispatch('permission/get');
});

export default router;
